<template>
  <div class="flex flex-col h-full">
    <vxe-card title="" class="w-full" :border="false">
      <AuForm ref="formRef" :formList="formList" @submit="search" />
    </vxe-card>

    <div class="flex-grow overflow-hidden mt-4">
      <AuTable ref="tableRef" v-bind="gridOption" @actionClick="actionClick">
        <template #status_default="{ row }">
          <el-tag :type="row.publishStatus === 1 ? 'success' : 'info'"
            >{{
              row.publishStatus === 1
                ? t("task_manage.form.putaway")
                : t("task_manage.form.sold_out")
            }}
          </el-tag>
        </template>
      </AuTable>
    </div>

    <VersionEditModal
      v-model="showEditModal"
      :form-data="rowData"
      @confirm="tableRef?.refresh()"
    />

    <IssueModal
      v-model="showIssueModel"
      :versionId="versionId"
      device-id-type="ATT-E"
      :release-fn="[taskVersionRelease, taskVersionReleaseList]"
    />
  </div>
</template>

<script setup lang="ts">
import { getCurrentInstance, reactive, ref } from "vue";
import { AuTable } from "@/components/AuTable";
import { AuForm } from "@/components/AuForm";
import {
  ACTION_TYPE,
  ObjectProps,
  PropDefines
} from "@/components/AuTable/type";
import { useRouter } from "vue-router";
import VersionEditModal from "./components/VersionEditModal.vue";
import { ElMessage } from "element-plus";
import IssueModal from "@/components/Autata/IssueModal.vue";
import {
  taskVersionDel,
  taskVersionGetList,
  TaskVersionProp,
  taskVersionPublish
} from "@/api/expiry/task";
import { taskVersionRelease, taskVersionReleaseList } from "@/api/expiry/task";
import { useI18n } from "vue-i18n";

const { t } = useI18n();

defineOptions({ name: "taskVersion" });

// region 声明ref变量集合
const { proxy } = getCurrentInstance();
const router = useRouter();

const checkList = ref([]);
const showModal = ref(false);

const showEditModal = ref(false);
const showIssueModel = ref(false);
const versionId = ref("");
const rowData = ref<TaskVersionProp>();

const formList = ref([
  // {
  //   type: "select",
  //   label: "task_manage.form.version_status",
  //   key: "publishStatus",
  //   placeholder: "task_manage.form.select_version_status",
  //   valueKey: "value",
  //   labelKey: "label",
  //   options: [
  //     {
  //       label: "task_manage.form.all",
  //       value: ""
  //     },
  //     {
  //       label: "task_manage.form.putaway",
  //       value: 1
  //     },
  //     {
  //       label: "task_manage.form.sold_out",
  //       value: 0
  //     }
  //   ]
  // },
  {
    type: "input",
    label: "task_manage.form.version_name",
    key: "name",
    placeholder: "task_manage.form.enter_version_name"
  }
]);
const gridOption = reactive<PropDefines>({
  isServerPage: true,
  showCheckbox: true,
  showIndex: false,
  columns: [
    { field: "name", title: "task_manage.form.name", align: "center" },
    { field: "note", title: "table.note", align: "center" },
    // {
    //   field: "publishStatus",
    //   title: "task_manage.form.status",
    //   slots: { default: "status_default" },
    //   align: "center"
    // },
    {
      field: "updateTime",
      title: "task_manage.form.update_time",
      align: "center",
      width: 190
    }
  ],
  actions: [
    ACTION_TYPE.TADD,
    ACTION_TYPE.TDELETE,
    // ACTION_TYPE.TPUTAWAY,
    // ACTION_TYPE.TOFFSHELVE,
    // ACTION_TYPE.VIEW,
    ACTION_TYPE.EDIT
  ],
  operateTools: [
    {
      key: ACTION_TYPE.VIEW,
      name: "table.viewTask"
    },
    {
      key: "issue",
      name: "table.issue"
    }
  ],
  dataSource: [],
  fetchConfig: {
    query: {
      service: (params: ObjectProps) => {
        const param = {
          ...params,
          filter: {
            ...formRef.value.getFormData()
          }
        };
        return taskVersionGetList(param);
      },
      param: () => formRef.value.getFormData()
    }
  }
});

const formRef = ref();
const tableRef = ref();
// endregion

// region 公共方法的集合

/**
 * 上架/下架
 * @param rows {TaskTypeListProp[]}
 * @param status {ACTION_TYPE.OFFSHELVE | ACTION_TYPE.PUTAWAY}
 */
const handleUpOrDown = (
  rows: TaskVersionProp[],
  status: ACTION_TYPE.OFFSHELVE | ACTION_TYPE.PUTAWAY
) => {
  const name = rows.map(v => v.name);
  const ids = rows.map(v => v.id);
  const statusText =
    status === ACTION_TYPE.OFFSHELVE
      ? t("task_manage.form.sold_out")
      : t("task_manage.form.putaway");
  const msg = t("task_manage.form.confirm_status_change", {
    status: statusText,
    name: name.join("、")
  });

  proxy.$auMessageBox.confirm(msg, t("notice.title")).then(() => {
    const param = {
      publishStatus: status === ACTION_TYPE.OFFSHELVE ? 0 : 1,
      ids
    };
    taskVersionPublish(param).then(res => {
      if (res.code === 200) {
        ElMessage({
          message: t("task_manage.form.status_change_success", {
            status: statusText
          }),
          type: "success"
        });
        tableRef.value.refresh();
      }
    });
  });
};

const handleDelete = () => {
  proxy.$auMessageBox
    .confirm(t("task_manage.form.delete_confirm"), t("notice.title"), {
      type: "error"
    })
    .then(() => {
      const checkRows = tableRef.value.getCheckboxRecords();
      if (checkRows.length > 0) {
        const ids = checkRows.map(item => item.id);
        taskVersionDel({ ids }).then(res => {
          if (res.code === 200) {
            ElMessage({
              message: t("notice.delete_success"),
              type: "success"
            });
            tableRef.value.refresh();
          }
        });
      }
    })
    .catch(() => {});
};
// endregion

// region 组件事件的集合
const search = () => {
  tableRef.value.refresh();
};

type ActionType = {
  key: ACTION_TYPE | string;
  row: TaskVersionProp;
};
const actionClick = ({ key, row }: ActionType) => {
  console.log(key, row);
  switch (key) {
    case ACTION_TYPE.VIEW:
      router.push({
        path: "/task/taskTime",
        query: {
          versionId: row.id,
          name: row.name,
          note: row.note,
          type: key
        }
      });
      break;
    case ACTION_TYPE.EDIT:
      rowData.value = row;
      showEditModal.value = true;
      break;
    case ACTION_TYPE.TADD:
      rowData.value = null;
      showEditModal.value = true;
      break;
    case ACTION_TYPE.PUTAWAY:
    case ACTION_TYPE.OFFSHELVE:
      handleUpOrDown([row], key);
      break;
    case ACTION_TYPE.TPUTAWAY:
      {
        const cKey = ACTION_TYPE.PUTAWAY;
        const cList = tableRef.value.getCheckboxRecords();
        handleUpOrDown(cList, cKey);
      }
      break;
    case ACTION_TYPE.TOFFSHELVE:
      {
        const cKey = ACTION_TYPE.OFFSHELVE;
        const cList = tableRef.value.getCheckboxRecords();
        handleUpOrDown(cList, cKey);
      }
      break;
    case ACTION_TYPE.TDELETE:
      handleDelete();
      break;
    case "issue":
      versionId.value = String(row.id);
      showIssueModel.value = true;
      break;
    default:
      break;
  }
};
// endregion
</script>
